from django.http import JsonResponse
from utils.services.InteriorCodeService import InteriorCodeService


class ResponseService(object):
    """
    统一项目信息返回结果服务类
    """

    def __init__(self):
        self.code = None
        self.msg = None
        self._data = dict()

    @staticmethod
    def sucess(msg=None, code=None):
        """
        组织成功响应信息
        :return:
        """
        r = ResponseService()
        r.code = code and code or InteriorCodeService.REQUEST_OK
        r.msg = msg and msg or '请求成功'
        return r

    @staticmethod
    def error(msg=None,code=None):
        """
        组织错误响应信息
        :return:
        """
        r = ResponseService()
        r.code = code and code or InteriorCodeService.REQUEST_FAIL
        r.msg = msg and msg or '请求失败'
        return r

    def data(self, obj=None, key=None):
        """统一后端返回的数据"""
        if key:
            self._data[key] = obj
        else:
            self._data = obj
        context = {
            'code': self.code,
            'msg': self.msg,
            'data': self._data
        }
        return JsonResponse(context)
